<template>
  <view>
    <!-- 头部导航栏 -->
    <view class="top-navigate" style="padding: 53px 10px 10px 10px;" @click="goBack">
      <view class="content cuIcon-back text-xl top-navigate-title"></view>
      <view class="text-xl top-navigate-title">填写取件信息</view>
    </view>
    <!-- 填写地址信息区域 -->
    <view class="edit-info-box">
      <!-- 收货地址 -->
      <view class="cu-form-group">
        <view class="margin-right-xs">地址:</view>
        <input v-model="newAddressInfo.name"></input>
        <button class="text-gray text-sm  btn-needs-address" @click="searchAddressInfo">请选择地址<view class="cuIcon-right">
          </view>
        </button>
      </view>
      <!-- 门牌号 -->
      <view class="cu-form-group">
        <view class="margin-right-xs ">门牌号:</view>
        <input placeholder="单元,楼层,门牌号等如2单元A601" name="input" v-model="newAddressInfo.address"></input>
      </view>
      <!-- 联系人 -->
      <view class="cu-form-group">
        <view class="margin-right-xs">联系人:</view>
        <input placeholder="联系人姓名" name="input" v-model="newAddressInfo.userName"></input>
      </view>
      <!-- 电话 -->
      <view class="cu-form-group">
        <view class="margin-right-xs">电话:</view>
        <input placeholder="请输入正确的手机号" name="input" v-model="newAddressInfo.phone"></input>
        <view class="cu-capsule radius">
          <view class='cu-tag bg-blue '>+86</view>
          <view class="cu-tag line-blue">中国大陆</view>
        </view>
      </view>

      <button class="cu-btn round bg-orange shadow lg flex" style="margin: 15px auto;width: 90%;"
        @click="addAddressInfoList" v-if="JSON.stringify(newAddressInfo) === '{}'">保存并使用</button>
      <button class="cu-btn round bg-orange shadow lg flex" style="margin: 15px auto;width: 90%;"
        @click="editAddressInfoList" v-else>编辑</button>
    </view>
    <!-- 我的收货地址列表 -->
    <view class="cu-list menu-avatar edit-info-box">
      <view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''" v-for="(item,index) in addressList"
        :key="index" @touchstart="ListTouchStart" @touchmove="ListTouchMove" @touchend="ListTouchEnd"
        :data-target="'move-box-' + index" @click="addNewInfo(item)">
        <view class="cu-item-address">
          <view class="text-cut text-black">
            {{item.address_name + item.address_detail}}
          </view>
          <view class="text-gray text-sm flex">
            <view style="margin-right:10px;">{{item.user_name}}</view>
            <view class="">{{item.user_phone}}</view>
          </view>
        </view>

        <view class="move" style="right: -10px;">
          <view class="bg-red" @click="deleteAddressInfo(item)">删除</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import deepClone from '../../helper/deep-clone.js'
  const db = uniCloud.database();
  export default {
    name: "order-address-info",
    data() {
      return {
        //存储更新的地址信息
        newAddressInfo: {},
        modalName: null,
        listTouchStart: 0,
        listTouchDirection: null,
      };
    },
    computed: {
      ...mapState('m_user', ['address', 'addressList', 'userinfo', 'addressEnd']),
    },
    methods: {
      ...mapMutations('m_user', ['updateAddress', 'updateAddressList', 'updateAddressEnd']),
      //选择地址事件
      searchAddressInfo() {
        uni.chooseLocation({
          success: (res) => {
            console.log(res);
            this.newAddressInfo = {
              name: res.name,
              address: res.address,
              userName: this.address.userName,
              phone: this.address.phone,
              latitude: res.latitude,
              longitude: res.longitude
            }
            // if (this.$parent.orderAddresInfoShowFlag === 1) {
            //   this.updateAddress(this.newAddressInfo)
            // } else if (this.$parent.orderAddresInfoShowFlag === 2) {
            //   this.updateAddressEnd(this.newAddressInfo)
            // }
          },
          fail: (err) => {
            uni.showToast({
              title: '获取位置失败'
            });
          }
        });
      },
      //新增用户地址信息按钮
      async addAddressInfoList() {
        this.newAddressInfo.user_id = this.userinfo._id
        console.log(this.newAddressInfo);
        const db = uniCloud.database();
        const {
          result: res
        } = await db.collection("my_address").add(this.newAddressInfo);
        if (res.id) {
          this.goBack()
          uni.$showMsg('新增地址成功！')
          this.$parent.getAddressList()
        } else {
          uni.$showMsg('新增地址失败！')
        }
        console.log(res);

      },
      //编辑用户地址信息
      async editAddressInfoList() {
        console.log(this.newAddressInfo);
        //判断是否是下单页面 做出相应操作
        console.log(this.$parent.ifPlaceOrder);
        if (this.$parent.ifPlaceOrder) {
          console.log('@@@@/ YES');
          this.$parent.longitude = this.newAddressInfo.longitude;
          this.$parent.latitude = this.newAddressInfo.latitude;
          this.$parent.covers[0].longitude = this.newAddressInfo.longitude;
          this.$parent.covers[0].latitude = this.newAddressInfo.latitude;
        }
        
        //根据父组件orderAddresInfoShowFlag判断地址是收货||取货地址
        if (this.$parent.orderAddresInfoShowFlag === 1) {
          this.updateAddress(this.newAddressInfo)
        } else if (this.$parent.orderAddresInfoShowFlag === 2) {
          this.updateAddressEnd(this.newAddressInfo)
        }
        this.goBack()
      },
      // 点击地址列表 为当前收货地址信息
      addNewInfo(item) {
        //判断是否是下单页面 做出相应操作
        if (this.$parent.ifPlaceSend) {
          this.$parent.longitude = item.address_longitude;
          this.$parent.latitude = item.address_latitude;
          this.$parent.covers[0].longitude = item.address_longitude;
          this.$parent.covers[0].latitude = item.address_latitude;
        }

        this.newAddressInfo = {
          name: item.address_name,
          latitude: item.address_latitude,
          longitude: item.address_longitude,
          userName: item.user_name,
          phone: item.user_phone,
          address: item.address_detail
        }
        //根据父组件orderAddresInfoShowFlag判断地址是收货||取货地址
        if (this.$parent.orderAddresInfoShowFlag === 1) {
          this.updateAddress(this.newAddressInfo)
        } else if (this.$parent.orderAddresInfoShowFlag === 2) {
          this.updateAddressEnd(this.newAddressInfo)
        }
        this.goBack()
      },
      goBack() {
        this.newAddressInfo = {}
        this.$parent.orderAddresInfoShow = false
        this.$parent.orderAddresInfoShowFlag = 0
      },
      //删除地址信息
      async deleteAddressInfo(item) {
        const {
          result: res
        } = await db.collection("my_address").where({
          _id: item._id
        }).remove();
        if (res.deleted === 1) {
          this.getAddressList()
          uni.$showMsg('删除地址成功！')
        } else {
          uni.$showMsg('删除地址失败！')
        }
        this.$parent.orderAddresInfoShow = true
        console.log(res);
      },
      // 获取数据库地址列表数据
      async getAddressList() {
        if(!this.userinfo._id) return uni.$showMsg('请先登录,即可获取个人地址信息列表！');
        const db = uniCloud.database();
        const {
          result: getAddressListInfo
        } = await db.collection("my_address").where({
          user_id: this.userinfo._id
        }).get();
        this.updateAddressList(getAddressListInfo.data)
      },
      // ListTouch触摸开始，获取触摸点距盒子左侧的距离
      ListTouchStart(e) {
        // console.log(e);
        this.listTouchStart = e.touches[0].pageX
      },
      // ListTouch计算方向，
      ListTouchMove(e) {
        this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
      },
      // ListTouch计算滚动
      ListTouchEnd(e) {
        if (this.listTouchDirection == 'left') {
          this.modalName = e.currentTarget.dataset.target
        } else {
          this.modalName = null
        }
        this.listTouchDirection = null
      },

    },
    mounted() {
      if (this.$parent.orderAddresInfoShowFlag === 1) {
        this.newAddressInfo = deepClone(this.address)
      } else if (this.$parent.orderAddresInfoShowFlag === 2) {
        this.newAddressInfo = deepClone(this.addressEnd)
      }
    },
    created() {
      this.getAddressList()
    }
  }
</script>

<style lang="scss">
  .top-navigate {
    display: flex;
    justify-content: left;
    align-items: center;

    .top-navigate-title {
      margin: 0 5px;
      font-weight: bold;
    }
  }

  .edit-info-box {
    padding: 5px;
    background-color: white;
    width: 95%;
    border-radius: 10px;
    margin: 0 auto 15px auto;

    .btn-needs-address {
      display: flex;
      align-items: center;
      margin: 0;
    }
  }

  .cu-item-address {
    width: 95%;
    line-height: 1.6em;
  }
</style>